package com.ksana.bean.factory.support;

import cn.hutool.core.lang.Assert;
import com.ksana.bean.BeanException;
import com.ksana.bean.factory.BeanFactory;
import com.ksana.bean.factory.FactoryBean;
import com.ksana.bean.factory.config.*;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
    protected List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeanException;
    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeanException;

    @Override
    public Object getBean(String name) throws BeanException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeanException {
        return doGetBean(name, args);
    }

    private Object doGetBean(String name, Object[] args) throws BeanException {
        Object object = getSingleton(name);
        if (object != null) {
            return getObjectForBeanInstance(object, name);
        }

        BeanDefinition mbd = getBeanDefinition(name);

        Object bean = createBean(name, mbd, args);

        if (mbd.isSingleton()) {
            registerSingleton(name, bean);
        }
        return getObjectForBeanInstance(bean, name);
    }

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        Assert.notNull(beanPostProcessor, "bean post processor 不能为空");
        this.beanPostProcessors.remove(beanPostProcessor);
        this.beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors() {
        return beanPostProcessors;
    }

    private Object getObjectForBeanInstance(Object beanInstance, String beanName) throws BeanException {
        if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        }

        Object object = getCachedObjectForFactoryBean(beanName);

        if (object == null) {
            FactoryBean<?> factoryBean = (FactoryBean<?>) beanInstance;
            object = getObjectFromFactoryBean(factoryBean, beanName);
        }

        return object;
    }
}
